package end.handler;

import java.lang.reflect.Method;
import java.util.HashMap;

import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

/**
 * 
 * LogHandler.java 2016-6-30
 *
 * Copyright zhaocj  Inc. All rights reserved.
 * Love Me Like Love Justin Bieber
 */
public class LogHandler implements InvocationHandler{
   
    private Object target; // 代理目标
    private Object proxy; // 代理对象

    private static HashMap<Class<?>, LogHandler> invoHandlers = new HashMap<Class<?>, LogHandler>();

    /**
     * 通过Class来生成动态代理对象Proxy
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
	public synchronized static<T> T getProxyInstance(Class<T> clazz){
        LogHandler invoHandler = invoHandlers.get(clazz);

        if(null == invoHandler){
            invoHandler = new LogHandler();
            try {
                T tar = clazz.newInstance();
                invoHandler.setTarget(tar);
                invoHandler.setProxy(Proxy.newProxyInstance(tar.getClass().getClassLoader(),
                        tar.getClass().getInterfaces(), invoHandler));
            } catch (Exception e) {
                e.printStackTrace();
            }
            invoHandlers.put(clazz, invoHandler);

        }

        return (T)invoHandler.getProxy();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object result = method.invoke(target, args); // 执行业务处理

        // 打印日志
     

        return result;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        return proxy;
    }

    public void setProxy(Object proxy) {
        this.proxy = proxy;
    }

}